#ifndef CON_CURRENT_H
#define CON_CURRENT_H

#include "Common.h"
#include "ThreadCache.h"
#include "PageCache.h"

static void *ConCurrentAlloc(size_t size)
{
  if (pTLSThreadCache == nullptr)
  {
    pTLSThreadCache = new ThreadCache;
  }

  void *ptr = nullptr;
  // 如果当前需要的span页数大于32页的话，直接向pageCache申请
  if(size > MAX_BYTES){    
    size_t alignSize = SizeClass::roundUp(size);    
    size_t nPage = alignSize >> PAGE_SHIFT;

    PageCache &pageCache = PageCache::getInstance();
    pageCache.getMtx().lock();
    Span *span = pageCache.newSpan(nPage);
    span->_batchSize = alignSize; 
    pageCache.getMtx().unlock();

    ptr = (void *)(span->_page_id << PAGE_SHIFT);

  }else{
    ptr = pTLSThreadCache->alloc(size);
  }
  return ptr;
}

static void ConCurrentDealloc(void *obj, size_t s) 
{
  // 获取当前内存块的页号是多少，通过页号找到所在span，span中存储着当前划分的内存块是多大
  PAGE_ID pageId = ((PAGE_ID)obj) >> PAGE_SHIFT;

  PageCache &pageCache = PageCache::getInstance();
  Span *span = pageCache.pageIdSpanMap(pageId);
  
  if(span == nullptr){
    int x = 10;
  }

  if(span->_batchSize > MAX_BYTES){
    pageCache.getMtx().lock();
    pageCache.dealloc(span);
    pageCache.getMtx().unlock();

  }
  else{
    pTLSThreadCache->dealloc(obj, span->_batchSize);
  }
}

#endif
